/**
 * 交易记录页面JS
 */
$(document).ready(function() {
    // 初始化日期选择器
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        language: 'zh-CN'
    });
    
    // 初始化交易记录表格
    var transactionTable = $('#transactionTable').DataTable({
        "serverSide": true,
        "processing": true,
        "ajax": {
            "url": "/api/transaction/list",
            "type": "POST",
            "data": function(d) {
                // 添加额外的请求参数
                d.transactionType = $('#transactionType').val();
                d.productName = $('#productName').val();
                d.warehouseId = $('#warehouseId').val();
                d.status = $('#status').val();
                d.startDate = $('#startDate').val();
                d.endDate = $('#endDate').val();
            }
        },
        "columns": [
            {"data": "transactionId"},
            {"data": "transactionType"},
            {"data": "productName"},
            {"data": "quantity"},
            {"data": "unit"},
            {"data": "amount"},
            {"data": "warehouseName"},
            {"data": "status"},
            {"data": "createTime"},
            {"data": null, "orderable": false}
        ],
        "columnDefs": [
            {
                "targets": 1,
                "render": function(data, type, row) {
                    var typeMap = {
                        'IN': '<span class="badge badge-success">采购入库</span>',
                        'OUT': '<span class="badge badge-danger">销售出库</span>',
                        'TRANSFER': '<span class="badge badge-info">库存调拨</span>',
                        'CHECK': '<span class="badge badge-warning">库存盘点</span>'
                    };
                    return typeMap[data] || data;
                }
            },
            {
                "targets": 7,
                "render": function(data, type, row) {
                    var statusMap = {
                        'PENDING': '<span class="badge badge-warning">待处理</span>',
                        'PROCESSING': '<span class="badge badge-info">处理中</span>',
                        'COMPLETED': '<span class="badge badge-success">已完成</span>',
                        'CANCELLED': '<span class="badge badge-danger">已取消</span>'
                    };
                    return statusMap[data] || data;
                }
            },
            {
                "targets": -1,
                "render": function(data, type, row) {
                    var buttons = '<button class="btn btn-sm btn-info mr-1 view-btn" data-id="' + row.transactionId + '"><i class="fas fa-eye"></i></button>';
                    
                    // 根据状态显示不同按钮
                    if (row.status === 'PENDING') {
                        buttons += '<button class="btn btn-sm btn-primary mr-1 edit-btn" data-id="' + row.transactionId + '"><i class="fas fa-edit"></i></button>';
                        buttons += '<button class="btn btn-sm btn-danger delete-btn" data-id="' + row.transactionId + '"><i class="fas fa-trash"></i></button>';
                    } else if (row.status === 'PROCESSING') {
                        buttons += '<button class="btn btn-sm btn-success complete-btn" data-id="' + row.transactionId + '"><i class="fas fa-check"></i></button>';
                    }
                    
                    return buttons;
                }
            }
        ],
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.21/i18n/Chinese.json"
        },
        "order": [[8, "desc"]], // 默认按创建时间降序排列
        "pageLength": 10
    });
    
    // 搜索按钮点击事件
    $('#searchBtn').click(function() {
        transactionTable.ajax.reload();
    });
    
    // 重置按钮点击事件
    $('#resetBtn').click(function() {
        $('#searchForm')[0].reset();
        transactionTable.ajax.reload();
    });
    
    // 新增交易按钮点击事件
    $('#addBtn').click(function() {
        // 重置表单
        $('#transactionForm')[0].reset();
        $('#transactionId').val('');
        
        // 加载产品和仓库下拉列表
        loadProducts();
        loadWarehouses();
        
        // 显示模态框
        $('#addEditTransactionModal').modal('show');
        $('#addEditTransactionModalLabel').text('新增交易');
    });
    
    // 编辑按钮点击事件
    $('#transactionTable').on('click', '.edit-btn', function() {
        var id = $(this).data('id');
        
        // 加载交易数据
        $.ajax({
            url: '/api/transaction/' + id,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var data = res.data;
                    
                    // 填充表单
                    $('#transactionId').val(data.transactionId);
                    $('#modalTransactionType').val(data.transactionType);
                    $('#modalProductId').val(data.productId);
                    $('#modalQuantity').val(data.quantity);
                    $('#modalUnit').val(data.unit);
                    $('#modalAmount').val(data.amount);
                    $('#modalWarehouseId').val(data.warehouseId);
                    $('#modalStatus').val(data.status);
                    $('#modalRemark').val(data.remark);
                    
                    // 显示模态框
                    $('#transactionModal').modal('show');
                    $('#transactionModalLabel').text('编辑交易');
                } else {
                    toastr.error('加载交易数据失败：' + res.message);
                }
            },
            error: function(xhr) {
                toastr.error('加载交易数据失败：' + xhr.statusText);
            }
        });
    });
    
    // 查看按钮点击事件
    $('#transactionTable').on('click', '.view-btn', function() {
        var id = $(this).data('id');
        
        // 加载交易详情
        $.ajax({
            url: '/api/transaction/' + id,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var data = res.data;
                    
                    // 填充详情
                    var typeMap = {
                        'IN': '采购入库',
                        'OUT': '销售出库',
                        'TRANSFER': '库存调拨',
                        'CHECK': '库存盘点'
                    };
                    
                    var statusMap = {
                        'PENDING': '待处理',
                        'PROCESSING': '处理中',
                        'COMPLETED': '已完成',
                        'CANCELLED': '已取消'
                    };
                    
                    $('#detailTransactionId').text(data.transactionId);
                    $('#detailTransactionType').text(typeMap[data.transactionType] || data.transactionType);
                    $('#detailProductName').text(data.productName);
                    $('#detailQuantity').text(data.quantity + ' ' + data.unit);
                    $('#detailAmount').text('¥' + data.amount.toFixed(2));
                    $('#detailWarehouseName').text(data.warehouseName);
                    $('#detailStatus').text(statusMap[data.status] || data.status);
                    $('#detailCreateTime').text(data.createTime);
                    $('#detailUpdateTime').text(data.updateTime || '-');
                    $('#detailRemark').text(data.remark || '-');
                    
                    // 显示模态框
                    $('#detailModal').modal('show');
                } else {
                    toastr.error('加载交易详情失败：' + res.message);
                }
            },
            error: function(xhr) {
                toastr.error('加载交易详情失败：' + xhr.statusText);
            }
        });
    });
    
    // 删除按钮点击事件
    $('#transactionTable').on('click', '.delete-btn', function() {
        var id = $(this).data('id');
        
        if (confirm('确定要删除此交易记录吗？')) {
            $.ajax({
                url: '/api/transaction/' + id,
                type: 'DELETE',
                success: function(res) {
                    if (res.code === 200) {
                        toastr.success('删除成功');
                        transactionTable.ajax.reload();
                    } else {
                        toastr.error('删除失败：' + res.message);
                    }
                },
                error: function(xhr) {
                    toastr.error('删除失败：' + xhr.statusText);
                }
            });
        }
    });
    
    // 完成按钮点击事件
    $('#transactionTable').on('click', '.complete-btn', function() {
        var id = $(this).data('id');
        
        if (confirm('确定要将此交易标记为已完成吗？')) {
            $.ajax({
                url: '/api/transaction/' + id + '/complete',
                type: 'PUT',
                success: function(res) {
                    if (res.code === 200) {
                        toastr.success('操作成功');
                        transactionTable.ajax.reload();
                    } else {
                        toastr.error('操作失败：' + res.message);
                    }
                },
                error: function(xhr) {
                    toastr.error('操作失败：' + xhr.statusText);
                }
            });
        }
    });
    
    // 保存交易按钮点击事件
    $('#saveTransactionBtn').click(function() {
        // 表单验证
        if (!$('#transactionForm').valid()) {
            return;
        }
        
        // 收集表单数据
        var formData = {
            transactionId: $('#transactionId').val() || null,
            transactionType: $('#modalTransactionType').val(),
            productId: $('#modalProductId').val(),
            productName: $('#modalProductId option:selected').text(),
            quantity: $('#modalQuantity').val(),
            unit: $('#modalUnit').val(),
            amount: $('#modalAmount').val(),
            warehouseId: $('#modalWarehouseId').val(),
            warehouseName: $('#modalWarehouseId option:selected').text(),
            status: $('#modalStatus').val(),
            remark: $('#modalRemark').val()
        };
        
        // 获取CSRF令牌
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        
        // 发送请求
        $.ajax({
            url: '/api/transaction/save',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            beforeSend: function(xhr) {
                // 添加CSRF令牌到请求头
                if (token && header) {
                    xhr.setRequestHeader(header, token);
                }
            },
            success: function(res) {
                if (res.code === 200) {
                    // 关闭模态框
                    $('#addEditTransactionModal').modal('hide');
                    // 刷新表格
                    $('#transactionTable').DataTable().ajax.reload();
                    // 显示成功消息
                    toastr.success('保存成功');
                } else {
                    toastr.error('保存失败：' + res.message);
                }
            },
            error: function(xhr) {
                toastr.error('保存失败：' + xhr.responseText);
            }
        });
    });
    
    // 导出按钮点击事件
    $('#exportBtn').click(function() {
        var queryParams = {
            transactionType: $('#transactionType').val(),
            productName: $('#productName').val(),
            warehouseId: $('#warehouseId').val(),
            status: $('#status').val(),
            startDate: $('#startDate').val(),
            endDate: $('#endDate').val()
        };
        
        var queryString = $.param(queryParams);
        window.location.href = '/api/transaction/export?' + queryString;
    });
    
    // 初始化表单验证
    $('#transactionForm').validate({
        rules: {
            modalTransactionType: {
                required: true
            },
            modalProductId: {
                required: true
            },
            modalQuantity: {
                required: true,
                number: true,
                min: 0
            },
            modalUnit: {
                required: true
            },
            modalAmount: {
                required: true,
                number: true,
                min: 0
            },
            modalWarehouseId: {
                required: true
            },
            modalStatus: {
                required: true
            }
        },
        messages: {
            modalTransactionType: {
                required: "请选择交易类型"
            },
            modalProductId: {
                required: "请选择产品"
            },
            modalQuantity: {
                required: "请输入数量",
                number: "请输入有效数字",
                min: "数量必须大于等于0"
            },
            modalUnit: {
                required: "请输入单位"
            },
            modalAmount: {
                required: "请输入金额",
                number: "请输入有效数字",
                min: "金额必须大于等于0"
            },
            modalWarehouseId: {
                required: "请选择仓库"
            },
            modalStatus: {
                required: "请选择状态"
            }
        },
        errorElement: 'div',
        errorPlacement: function(error, element) {
            error.addClass('invalid-feedback');
            element.closest('.form-group').append(error);
        },
        highlight: function(element) {
            $(element).addClass('is-invalid');
        },
        unhighlight: function(element) {
            $(element).removeClass('is-invalid');
        }
    });
    
    // 加载仓库下拉框数据
    loadWarehouses();
    
    // 加载产品下拉框数据
    loadProducts();
});

// 加载仓库列表
function loadWarehouses() {
    $.ajax({
        url: '/api/warehouse/list',
        type: 'GET',
        success: function(res) {
            if (res.code === 200) {
                var warehouses = res.data;
                var options = '<option value="">全部仓库</option>';
                var modalOptions = '<option value="">请选择仓库</option>';
                
                for (var i = 0; i < warehouses.length; i++) {
                    var warehouse = warehouses[i];
                    options += '<option value="' + warehouse.id + '">' + warehouse.name + '</option>';
                    modalOptions += '<option value="' + warehouse.id + '">' + warehouse.name + '</option>';
                }
                
                $('#warehouseId').html(options);
                $('#modalWarehouseId').html(modalOptions);
            } else {
                toastr.error('加载仓库列表失败：' + res.message);
            }
        },
        error: function(xhr) {
            toastr.error('加载仓库列表失败：' + xhr.statusText);
        }
    });
}

// 加载产品列表
function loadProducts() {
    $.ajax({
        url: '/api/product/list',
        type: 'GET',
        success: function(res) {
            if (res.code === 200) {
                var products = res.data;
                var options = '<option value="">全部产品</option>';
                var modalOptions = '<option value="">请选择产品</option>';
                
                for (var i = 0; i < products.length; i++) {
                    var product = products[i];
                    options += '<option value="' + product.name + '">' + product.name + '</option>';
                    modalOptions += '<option value="' + product.id + '">' + product.name + '</option>';
                }
                
                $('#productName').html(options);
                $('#modalProductId').html(modalOptions);
            } else {
                toastr.error('加载产品列表失败：' + res.message);
            }
        },
        error: function(xhr) {
            toastr.error('加载产品列表失败：' + xhr.statusText);
        }
    });
}

// 产品选择变更时自动填充单位
$('#modalProductId').change(function() {
    var productId = $(this).val();
    if (!productId) {
        $('#modalUnit').val('');
        return;
    }
    
    $.ajax({
        url: '/api/product/' + productId,
        type: 'GET',
        success: function(res) {
            if (res.code === 200) {
                $('#modalUnit').val(res.data.unit);
            }
        }
    });
}); 